package com.joy.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.joy.eduservice.entity.EduSubject;
import com.joy.eduservice.entity.excel.SubjectData;
import com.joy.eduservice.service.EduSubjectService;
import com.joy.servicebase.exceptionHandler.GuliException;

/**
 * @author 焦恩越
 * @create 2021-12-01-19:29
 */
public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

    //监听器没有也不能交给spring管理，需要手动new对象，也不能调用service里面的东西，也不能注入其他对象
    //不能实现数据库操作
    public EduSubjectService eduSubjectService;

    public SubjectExcelListener() {
    }

    public SubjectExcelListener(EduSubjectService eduSubjectService) {
        this.eduSubjectService = eduSubjectService;
    }

    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if(subjectData == null){
            throw new GuliException(20001,"数据文件为空");
        }
        //一行一行读取，每次读取有两个值，第一个值一级分类，第二个值二级分类
        EduSubject eduOneSubject = this.exitOneSubject(eduSubjectService, subjectData.getOneSubjectName());
        if(eduOneSubject == null){//没有相同的一级分类，进行添加

            eduOneSubject = new EduSubject();
            eduOneSubject.setParentId("0");//设置一级分类id
            eduOneSubject.setTitle(subjectData.getOneSubjectName());//设置一级分类名称
            eduSubjectService.save(eduOneSubject);
        }
        //添加二级分类
        //判断二级分类是否重复
        String pid = eduOneSubject.getId();//二级分类的父id值就是一级分类的id值
        EduSubject exitTwoSubject = this.exitTwoSubject(eduSubjectService, subjectData.getTowSubjectName(), pid);
        if(exitTwoSubject == null){//没有相同的二级分类，进行添加
            exitTwoSubject = new EduSubject();
            exitTwoSubject.setParentId(pid);
            exitTwoSubject.setTitle(subjectData.getTowSubjectName());//二级分类名称
            eduSubjectService.save(exitTwoSubject);
        }
    }

    //判断一级分类不能重复添加
    private EduSubject exitOneSubject(EduSubjectService eduSubjectService,String name){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();//相当于自动动态的拼接SQL
        wrapper.eq("title",name);//添加条件
        wrapper.eq("parent_id","0");//添加条件
        EduSubject oneSubject = eduSubjectService.getOne(wrapper);
        return oneSubject;

    }

    //判断二级分类不能重复添加
    private EduSubject exitTwoSubject(EduSubjectService eduSubjectService,String name,String pid){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",pid);
        EduSubject towSubject = eduSubjectService.getOne(wrapper);
        return towSubject;
    }
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
